package com.cheer.ba.view.activity;

import android.content.Intent;
import android.os.CountDownTimer;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.text.Editable;
import android.text.InputType;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.method.DigitsKeyListener;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;

import com.bigkoo.svprogresshud.SVProgressHUD;
import com.cheer.ba.R;
import com.cheer.ba.constant.CodeStatus;
import com.cheer.ba.constant.Constants;
import com.cheer.ba.constant.IntentCode;
import com.cheer.ba.constant.IntentKey;
import com.cheer.ba.constant.Type;
import com.cheer.ba.presenter.impl.LoginPresenter;
import com.cheer.ba.service.BackGroundService;
import com.cheer.ba.utils.NetUtils;
import com.cheer.ba.utils.StringUtils;
import com.cheer.ba.utils.ToastUtil;
import com.cheer.ba.view.base.BaseCommAty;
import com.litesuits.common.utils.HexUtil;
import com.litesuits.common.utils.MD5Util;

import org.json.JSONException;
import org.json.JSONObject;

import butterknife.BindView;
import butterknife.OnClick;
import cn.smssdk.EventHandler;
import cn.smssdk.SMSSDK;

/**
 * 忘记登录密码
 *
 * @author HQ
 *         created at 2017/3/9 0009 10:01
 */
public class ForgotPwAty extends BaseCommAty {

    /**
     * 手机号
     */
    @BindView(R.id.id_forget_phone_edit)
    EditText mEditPhone;
    private String mPhone;
    @BindView(R.id.id_clear_phone)
    ImageView mImgClearPhone;

    /**
     * 发送验证码
     */
    @BindView(R.id.id_forget_code_btn)
    Button mBtnSendCode;

    /**
     * 验证码
     */
    @BindView(R.id.id_forget_code_edit)
    EditText mEditCode;
    private String mCode;
    @BindView(R.id.id_clear_code)
    ImageView mImgClearCode;

    /**
     * 新密码
     */
    @BindView(R.id.id_input_pw_edit)
    EditText mEditPw;
    private String mSaveNewPw;
    @BindView(R.id.id_clear_pw)
    ImageView mImgClearPw;
    //密码是否可见
    @BindView(R.id.id_watch_pass)
    ImageView mImgWatchPw;


    /**
     * 再次输入新密码
     */
    @BindView(R.id.id_input_re_pw_edit)
    EditText mEditReNewPw;
    private String mSaveReNewPw;
    @BindView(R.id.id_clear_re_pw)
    ImageView mImgClearRePw;
    //密码是否可见
    @BindView(R.id.id_watch_re_pass)
    ImageView mImgWatchRePw;

    /**
     * 倒计时类
     */
    private MyCount mc;

    private static final int SUBMIT_VERIFICATION_CODE_COMPLETE = 1;
    private static final int GET_VERIFICATION_CODE_COMPLETE = 2;
    private static final int RESULT_ERROR = 3;
    //获取验证码太频繁
    private static final int RESULT_ERROR_1 = 4;
    //获取验证码失败
    private static final int RESULT_ERROR_2 = 5;
    //提交验证失败
    private static final int RESULT_ERROR_3 = 6;

    /**
     * 短信回调
     */
    private EventHandler en = new EventHandler() {
        @Override
        public void afterEvent(int event, int result, Object data) {
            Log.d("huangqiang", event + "---" + result + "===" + data.toString());
            //解析注册结果
            if (result == SMSSDK.RESULT_COMPLETE) {
                //回调完成
                if (event == SMSSDK.EVENT_SUBMIT_VERIFICATION_CODE) {
                    //提交验证码成功
                    handler.sendEmptyMessage(GET_VERIFICATION_CODE_COMPLETE);
                } else if (event == SMSSDK.EVENT_GET_VERIFICATION_CODE) {
                    //获取验证码成功
                    handler.sendEmptyMessage(SUBMIT_VERIFICATION_CODE_COMPLETE);
                } else if (event == SMSSDK.EVENT_GET_SUPPORTED_COUNTRIES) {
                    //返回支持发送验证码的国家列表
                }
            } else if (result == SMSSDK.RESULT_ERROR) {
                if (null == data) {
                    handler.sendEmptyMessage(RESULT_ERROR_1);
                    return;
                }
                //处理失败结果
                Throwable throwable = (Throwable) data;
                throwable.printStackTrace();
                JSONObject object;
                try {
                    object = new JSONObject(throwable.getMessage());
                    // 错误代码
                    int status = object.optInt("status");
                    // 错误描述
                    String detail = object.optString("detail");
                    if (status == 468) {
                        handler.sendEmptyMessage(RESULT_ERROR_3);
                    } else {
                        handler.sendEmptyMessage(RESULT_ERROR_2);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                    handler.sendEmptyMessage(RESULT_ERROR_1);
                }
            }
        }
    };

    private Handler handler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {
                case SUBMIT_VERIFICATION_CODE_COMPLETE:
                    ToastUtil.showToast("获取成功");
                    break;
                case GET_VERIFICATION_CODE_COMPLETE:
//                    ToastUtil.showToast("提交验证成功");
                    //忘记密码，重置密码
                    ((LoginPresenter) presenter).forgotPw(mPhone, HexUtil.encodeHexStr(MD5Util.md5(mSaveNewPw)), mCode);
                    break;
                case RESULT_ERROR_1:
                    SVProgressHUD.showInfoWithStatus(aty, getString(R.string.get_more_code));
                    break;
                case RESULT_ERROR_2:
                    SVProgressHUD.showInfoWithStatus(aty, getString(R.string.get_code_error));
                    handlerByPage(CodeStatus.Gegeneral.ERROR_DATA, CodeStatus.Gegeneral.ERROR_DATA, getString(R.string.get_code_error));
                    break;
                case RESULT_ERROR_3:
                    SVProgressHUD.showInfoWithStatus(aty, getString(R.string.check_code_fail));
                    break;
            }
        }
    };

    @Nullable
    @Override
    public View loadView(LayoutInflater inflater, View childView) {
        return super.loadView(inflater, inflater.inflate(R.layout.aty_forget_pw, null));
    }

    @Override
    public void initPresenter() {
        presenter = new LoginPresenter();
    }

    @Override
    public boolean hasDataInPage() {
        return true;
    }

    @Override
    public void initView() {
        setTitleText(getString(R.string.forget_title));
        if (BackGroundService.time_code != 0) {
            startCount(BackGroundService.time_code);
        }
    }

    @Override
    public void initData() {
//        SMSSDK.registerEventHandler(en);

        mEditPhone.addTextChangedListener(new TextWatcher() {
            @Override
            public void onTextChanged(CharSequence s, int arg1, int arg2,
                                      int arg3) {
                mPhone = s + "";
                if (!StringUtils.isEmpty(mPhone)) {
                    mImgClearPhone.setVisibility(View.VISIBLE);
                } else {
                    mImgClearPhone.setVisibility(View.GONE);
                }
            }

            @Override
            public void beforeTextChanged(CharSequence arg0, int arg1,
                                          int arg2, int arg3) {
            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });

        mEditCode.addTextChangedListener(new TextWatcher() {
            @Override
            public void onTextChanged(CharSequence s, int arg1, int arg2,
                                      int arg3) {
                mCode = s + "";
                if (!StringUtils.isEmpty(mCode)) {
                    mImgClearCode.setVisibility(View.VISIBLE);
                } else {
                    mImgClearCode.setVisibility(View.GONE);
                }
            }

            @Override
            public void beforeTextChanged(CharSequence arg0, int arg1,
                                          int arg2, int arg3) {
            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });

        mEditPw.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                mSaveNewPw = s + "";
                if (StringUtils.isEmpty(mSaveNewPw)) {
                    mImgClearPw.setVisibility(View.GONE);
                } else {
                    mImgClearPw.setVisibility(View.VISIBLE);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });

        mEditPw.setKeyListener(new DigitsKeyListener() {
            @Override
            public int getInputType() {
                return InputType.TYPE_TEXT_VARIATION_PASSWORD;
            }

            @Override
            protected char[] getAcceptedChars() {
                char[] data = getResources().getString(
                        R.string.edit_only_can_input).toCharArray();
                return data;
            }
        });

        mEditReNewPw.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                mSaveReNewPw = s + "";
                if (StringUtils.isEmpty(mSaveReNewPw)) {
                    mImgClearRePw.setVisibility(View.GONE);
                } else {
                    mImgClearRePw.setVisibility(View.VISIBLE);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });

        mEditReNewPw.setKeyListener(new DigitsKeyListener() {
            @Override
            public int getInputType() {
                return InputType.TYPE_TEXT_VARIATION_PASSWORD;
            }

            @Override
            protected char[] getAcceptedChars() {
                char[] data = getResources().getString(
                        R.string.edit_only_can_input).toCharArray();
                return data;
            }
        });
        String phone = getIntent().getStringExtra(IntentKey.General.KEY_DES);
        if (!StringUtils.isEmpty(phone)) {
            mEditPhone.setText(phone);
        }
    }

    /**
     * 启动倒计时
     */
    private void startCount(long time) {
        mBtnSendCode.setEnabled(false);
        if (null != mc) {
            mc.cancel();
            mc = null;
        }
        mc = new MyCount(time, 1000);
        mc.start();
    }

    /**
     * 倒计时类
     */
    private class MyCount extends CountDownTimer {
        public MyCount(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onTick(long millisUntilFinished) {
            mBtnSendCode.setText(millisUntilFinished / 1000
                    + getString(R.string.regist_second));
        }

        @Override
        public void onFinish() {
            mBtnSendCode.setText(getResources().getString(
                    R.string.send_check_code));
            mBtnSendCode.setEnabled(true);
        }
    }

    /**
     * 检查输入信息格式是否正确
     *
     * @return
     */
    public boolean checkData() {
        if (StringUtils.isMobile(mPhone)) {
            if (StringUtils.isEmpty(mCode)) {
                SVProgressHUD.showInfoWithStatus(aty, getString(R.string.input_check_code));
            } else {
                if (StringUtils.isEmpty(mSaveNewPw) || mSaveNewPw.length() > 18 || mSaveNewPw.length() < 6) {
                    SVProgressHUD.showInfoWithStatus(aty, getString(R.string.setting_login_pwd));
                } else {
                    if (StringUtils.isNumRic(mSaveNewPw) || StringUtils.isLetterRic(mSaveNewPw)) {
                        SVProgressHUD.showInfoWithStatus(aty, getString(R.string.pw_had_num_letter));
                    } else {
                        if (!TextUtils.equals(mSaveNewPw, mSaveReNewPw)) {
                            SVProgressHUD.showInfoWithStatus(aty, getString(R.string.no_equal_pw));
                        } else {
                            return true;
                        }
                    }
                }
            }
        } else {
            SVProgressHUD.showInfoWithStatus(aty, getString(R.string.phone_error));
        }
        return false;
    }

    @OnClick({R.id.id_clear_phone, R.id.id_clear_code, R.id.id_clear_pw, R.id.id_watch_pass, R.id.id_clear_re_pw, R.id.id_watch_re_pass, R.id.id_forget_code_btn, R.id.id_sure_btn})
    public void onClick(View view) {
        switch (view.getId()) {
            //清除手机号
            case R.id.id_clear_phone:
                mEditPhone.setText("");
                break;
            //清除验证码
            case R.id.id_clear_code:
                mEditCode.setText("");
                break;
            //清除密码
            case R.id.id_clear_pw:
                mEditPw.setText("");
                break;
            //查看密码
            case R.id.id_watch_pass:
                int length = TextUtils.isEmpty(mEditPw.getText()) ? 0 : mEditPw.getText().length();
                if (mEditPw.getTransformationMethod() == PasswordTransformationMethod.getInstance()) {
                    mEditPw.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                    mImgWatchPw.setImageDrawable(getResources().getDrawable(R.drawable.ic_eye_on));
                } else {
                    mEditPw.setTransformationMethod(PasswordTransformationMethod.getInstance());
                    mImgWatchPw.setImageDrawable(getResources().getDrawable(R.drawable.ic_eye_off));
                }
                mEditPw.setSelection(length);
                break;
            case R.id.id_clear_re_pw:
                mEditReNewPw.setText("");
                break;
            case R.id.id_watch_re_pass:
                int length1 = TextUtils.isEmpty(mEditReNewPw.getText()) ? 0 : mEditReNewPw.getText().length();
                if (mEditReNewPw.getTransformationMethod() == PasswordTransformationMethod.getInstance()) {
                    mEditReNewPw.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                    mImgWatchRePw.setImageDrawable(getResources().getDrawable(R.drawable.ic_eye_on));
                } else {
                    mEditReNewPw.setTransformationMethod(PasswordTransformationMethod.getInstance());
                    mImgWatchRePw.setImageDrawable(getResources().getDrawable(R.drawable.ic_eye_off));
                }
                mEditReNewPw.setSelection(length1);
                break;
            //获取短信验证码
            case R.id.id_forget_code_btn:
                if (!StringUtils.isMobile(mPhone)) {
                    SVProgressHUD.showInfoWithStatus(aty, getString(R.string.phone_error));
                    return;
                }
                if (!NetUtils.isNetworkConnected(aty)) {
                    SVProgressHUD.showInfoWithStatus(aty, getString(R.string.no_net_work));
                } else {
                    BackGroundService.countDownCode(Constants.COUNTDOWN * 1000);
                    startCount(Constants.COUNTDOWN * 1000);
                    ((LoginPresenter) presenter).getVeriCode(mPhone, Type.VERIFY_CODE, "");
                    //获取短信验证码
//                    SMSSDK.getVerificationCode("86", mPhone);
                }
                break;
            //确定修改
            case R.id.id_sure_btn:
                if (com.cheer.ba.utils.CountDownTimer.isFastClick()) {
                    return;
                }
                if (checkData()) {
                    //提交验证
//                    SMSSDK.submitVerificationCode("86", mPhone, mCode);
                    ((LoginPresenter) presenter).forgotPw(mPhone, HexUtil.encodeHexStr(MD5Util.md5(mSaveNewPw)), mCode);
                }
                break;
        }
    }

    /**
     * 处理接口返回数据
     *
     * @author HQ
     * created at 2017/3/8 0008 11:30
     */
    @Override
    public void handlerByPage(int flag1, int flag2, String string) {
        if (flag1 == CodeStatus.Gegeneral.DATA_SUCCESS_FULL) {
            //获取短信验证码成功

        } else if (flag1 == CodeStatus.Gegeneral.ERROR_DATA) {
            //获取短信验证码失败
            SVProgressHUD.showInfoWithStatus(aty, string);
            mBtnSendCode
                    .setText(getString(R.string.send_check_code));
            mBtnSendCode.setEnabled(true);
            if (mc != null) {
                mc.cancel();
            }
            if (null != BackGroundService.countCode) {
                BackGroundService.countCode.cancel();
            }
            BackGroundService.time_code = 0;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (null != mc) {
            mc.cancel();
        }
//        SMSSDK.unregisterEventHandler(en);
    }

    @Override
    public <T> void updateView(T t) {
        //重置登录密码成功
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                Intent intent = new Intent();
                intent.putExtra(IntentKey.General.KEY_DES, mPhone);
                setResult(IntentCode.Forget.FORGET_RESULT_CODE, intent);
                finish();
            }
        }, 2000);
    }
}
